package com.zbf.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zbf.common.utils.JWTUtis;
import com.zbf.core.exception.AuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 作者: LCG
 * 日期: 2020/6/1 08:48
 * 描述: 权限校验拦截器
 */

@Component
public class AutherInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求的路径（不包括域名端口前缀）
        String requestURI = request.getRequestURI();
        //获取Token
        String token = request.getHeader("token");
        //解析Token
        JSONObject jsonObject = JWTUtis.decodeJwtTocken(token);
        //查看用户是否包含某个权限
        String authUrlId="AUTHURL"+jsonObject.get("id");
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(authUrlId, requestURI);
        //判断用户权限是否包含某个请求路径
        if(aBoolean){
            return super.preHandle(request, response, handler);
        }else{
            throw new AuthException("没有权限");
        }


    }
}
